import { uid } from '@/utils';
import { useState, useEffect } from 'react';
import classNames from 'classnames';
import React, { useRef } from 'react';
import ReactDOM from 'react-dom';
import styles from './index.less';
import { message } from 'antd';
import Item from 'antd/lib/list/Item';
import request from '@/utils/request';
import { loadScript, isImg } from '@/utils';
import { allGet } from '@/services/pc';
import { history } from 'umi';
import * as ABC from '@/pages/pc/video/player/abc';

interface ScoreProps {
  onSubmit: (score) => void;
  onClose?: () => void;
  data: VideoDateItem;
  isLast: boolean;
}
const scoresMap = {
  1: 'B',
  2: 'A',
  3: 'A+',
  4: 'S',
};

const transformReward = (data = []) => {
  return [
    {
      type: 'B',
      text:
        data?.[1]?.[1] != 0 || data?.[1]?.[2] != 0
          ? data?.[1]?.[1] != 0
            ? `${data?.[1]?.[1]}元RMB`
            : `${data?.[1]?.[2]}点CG券`
          : '',
    },

    {
      type: 'A',
      text:
        data?.[2]?.[1] != 0 || data?.[2]?.[2] != 0
          ? data?.[2]?.[1] != 0
            ? `${data?.[2]?.[1]}元RMB`
            : `${data?.[2]?.[2]}点CG券`
          : '',
    },

    {
      type: 'A+',
      text:
        data?.[3]?.[1] != 0 || data?.[3]?.[2] != 0
          ? data?.[3]?.[1] != 0
            ? `${data?.[3]?.[1]}元RMB`
            : `${data?.[3]?.[2]}点CG券`
          : '',
    },
    {
      type: 'S',
      text:
        data?.[4]?.[1] != 0 || data?.[4]?.[2] != 0
          ? data?.[4]?.[1] != 0
            ? `${data?.[4]?.[1]}元RMB`
            : `${data?.[4]?.[2]}点CG券`
          : '',
    },
  ];
};
const Score: React.FC<ScoreProps> = ({ onSubmit, detail = {}, data, isLast, onClose }) => {
  const [index, setIndex] = useState(data.score);

  const disabled = !!data.score;
  const handleClick = (index) => {
    if (disabled) {
      return;
    }
    setIndex(index);
  };
  const handleSubmit = () => {
    onSubmit(index);
  };

  const text = () => {
    if (isLast) {
      if (data.score) {
        return '关闭';
      }
      return '提交';
    }
    return data.score ? '下一份' : '提交，批改下一份';
  };
  const reward = transformReward(detail.reward);
  return (
    <div className={classNames(styles.score, { [styles.disabled]: disabled })}>
      <img loading="lazy" className={styles.title} src={require('./images/title.png')} />
      <div className={classNames(styles['process-wrapper'], styles[`score-${index}`])}>
        <div className={styles['score-wrapper']}>
          <div
            className={classNames(styles['score-item'], styles.b)}
            onClick={() => handleClick(1)}
          >
            <i className={styles.icon} />
            <i className={styles.checked} />
            不及格
          </div>
          <div
            className={classNames(styles['score-item'], styles.a)}
            onClick={() => handleClick(2)}
          >
            <i className={styles.icon} />
            <i className={styles.checked} />
            及格
          </div>
          <div
            className={classNames(styles['score-item'], styles.as)}
            onClick={() => handleClick(3)}
          >
            <i className={styles.icon} />
            <i className={styles.checked} />
            优秀
          </div>
          <div
            className={classNames(styles['score-item'], styles.s)}
            onClick={() => handleClick(4)}
          >
            <i className={styles.icon} />
            <i className={styles.checked} />
            <i className={styles.left} />
            <i className={styles.top} />
            <i className={styles.right} />
            <i className={styles.bottom} />
            大神
          </div>
        </div>
        <i className={classNames(styles.opacitYprocess, styles[index])} />
        <i className={classNames(styles.process, styles[`process-${index}`])} />
      </div>
      <div className={styles.des}>
        <div className={styles.fileds}>
          <span className={styles.key}>作业等级：</span>
          <span className={styles.value}>{scoresMap[index] || '-'}</span>
        </div>
        <div className={styles.fileds}>
          <span className={styles.key}>奖励：</span>
          <span className={styles.value}>{reward[index - 1]?.text || '-'}</span>
        </div>
      </div>
      <div className={styles.buttons}>
        <div className={styles.button} onClick={() => onClose?.()}>
          取消
        </div>
        <div
          className={classNames(styles.button, styles.submit, { [styles.disabled]: !index })}
          onClick={handleSubmit}
        >
          {text()}
        </div>
      </div>
    </div>
  );
};

interface VideoDateItem {
  url?: string;
  vid?: string;
  score?: any;
  username?: string;
  studentnum?: string;
  classname?: string;
  avatar?: string;
}

interface OriginVideoPlayerModalProps {
  container?: HTMLElement;
  visible: boolean;
  defaultIndex?: number;
  data: any[];
  onClose?: () => void;
  onScoreSubmit?: (score, index) => Promise<boolean>;
  destroyOnClose?: boolean;
  type: 'star' | 'score' | 'video' | 'plv' | 'detail' | 'bjy';
  // 是否显示下载作业源文件
  showDownLoadWorkFile?: boolean;
  vid?: any;
}

const OriginVideoPlayerModal: React.FC<OriginVideoPlayerModalProps> = ({
  type,
  container = document.body,
  visible,
  data = [],
  defaultIndex = 0,
  onClose,
  destroyOnClose = false,
  vid,
  showDownLoadWorkFile,
  onScoreSubmit = () => Promise.resolve(true),
}) => {
  const [index, setIndex] = useState(defaultIndex);
  const currentData = data[index] as any;
  const videoRef = useRef<HTMLVideoElement>(null);
  if (destroyOnClose && !visible) {
    return null;
  }
  const kongfn = (event) => {
    if (event.keyCode === 32) {
      event.preventDefault();
      if (videoRef.current?.paused) {
        videoRef.current.play();
      } else {
        videoRef.current?.pause();
      }
    }
  };

  useEffect(() => {
    document.addEventListener('keydown', kongfn);
    return () => {
      document.removeEventListener('keydown', kongfn);
    };
  }, []);
  useEffect(() => {
    if (visible === true) {
      // window.scrollTo({
      //     left: 0,
      //     top: 0,
      //     behavior: 'smooth'//或'auto'
      // });
    }
  }, [visible]);

  // 保利威
  const player = useRef<any>(null);
  useEffect(() => {
    if (type === 'bjy') {
      loadPlayer('bjy');
    } else {
      if (!window.polyvPlayer) {
        loadScript('https://player.polyv.net/script/player.js').then(() => {
          loadPlayer();
        });
      } else {
        loadPlayer();
      }
    }
  }, []);
  const loadPlayer = async (type) => {
    if (!data?.[0]?.vid) return;
    const response = await allGet({
      params: { mod: 'baijiayun', do: 'play', version: 'pc1.0', vid: data?.[0]?.vid },
    });
    if (type === 'bjy') {
      const key = response.data?.marquee.substr(-16);
      const playSafe1 = response.data?.token;
      const timestamp = response.data?.timestamp;
      const decrypt = ABC.AES.decrypt;
      const token = decrypt(playSafe1, key, timestamp + '');
      player.current = new window.BPlayer({
        container: document.getElementById('zhy-cjjoy-video-player'), // 设置播放器初始化的父容器
        memory: true, // 是否开启记忆播放
        preload: 'meta', // 预加载，推荐设置 meta
        vid: data?.[0]?.vid, // 百家云后台视频id
        token, // 视频id 对应token
      });
    } else {
      player.current = window.polyvPlayer({
        wrap: '#zhy-cjjoy-video-player',
        width: '100%',
        height: '100%',
        autoplay: true,
        code: response?.data?.code,
        playsafe: response?.data?.playSafe,
        vid: data?.[0]?.vid,
      });
    }
  };
  const handlePrev = async () => {
    if (index > 0) {
      await getDetail((data[index - 1] as any)?.bid, index - 1);
      setIndex(index - 1);
    }
  };
  const handleNext = async () => {
    if (index < data.length - 1) {
      await getDetail((data[index + 1] as any)?.bid, index + 1);
      setIndex(index + 1);
    }
  };

  // 作业详情
  const [detail, setDetail] = useState<any>({});
  const [loading, setLoading] = useState(false);
  const getDetail = async (bid, _index) => {
    const response = await allGet({ params: { mod: 'busywork', bid, version: 'pc1.0' } });
    if (response?.data.videourl) {
      data[_index].url = response?.data.videourl;
    }
    setDetail(response?.data ?? {});
    setLoading(true);
  };

  useEffect(() => {
    if (type === 'video' || type === 'plv' || type === 'bjy') return;
    getDetail(currentData?.bid, index);
  }, []);

  const handleScoreSubmit = async (score) => {
    const result = await onScoreSubmit(score, index);
    if (result !== true) return;
    if (!data[index].score) {
      data[index].score = score;
    }
    if (index === data.length - 1) {
      return onClose?.();
    }
    handleNext();
  };
  const handleGood = async () => {
    const response = await allGet({
      params: { mod: 'busywork', do: 'good', version: 'pc1.0', bid: currentData?.bid },
    });
    if (response.success) {
      getDetail(currentData?.bid, index);
    }
  };

  const goStudent = () => {
    window.open(`/personal?uid=${currentData.uid}`);
    onClose?.();
  };

  const goClassDetail = () => {
    window.open(`/center/courses/detail/${currentData.classid}`);
    onClose?.();
  };

  const hasVideoUrl = () => {
    if (currentData.url) {
      return (
        <video
          className={styles.video}
          ref={videoRef}
          loop
          autoPlay
          controls
          controlsList="nodownload"
          disablePictureInPicture
          preload="metadata"
          src={currentData?.url}
        >
          <p>您的浏览器不支持html5播放器，请更换浏览器进行尝试</p>
        </video>
      );
    }
    return (
      <div className={styles.zmwrapper}>
        <i className={styles.zmwrapperIcon} />
        <div className={styles.zmwrapperText}>视频正在转码，稍后来查看</div>
      </div>
    );
  };

  const content = (
    <div
      className={classNames(styles.videoPlayModal, styles[`videoPlayModal-${type}`])}
      style={{ display: visible ? 'block' : 'none' }}
    >
      <i className={styles.mask} onClick={() => onClose?.()} />
      <div className={styles.main}>
        {(type === 'star' || type === 'score' || type === 'detail') && (
          <div className={styles.header}>
            <img
              loading="lazy"
              className={styles.preimg}
              src={detail?.classthumb}
              onClick={goClassDetail}
            />
            <div className={styles.text} onClick={goClassDetail}>
              {detail?.coursename}
            </div>
          </div>
        )}
        <div
          className={classNames(styles.contentWrapper, {
            [styles.contentWrapperImg]: isImg(currentData.url),
          })}
        >
          {type !== 'plv' && type !== 'bjy' && (
            <>
              {isImg(currentData.url) ? (
                <img loading="lazy" className={styles.img} src={currentData.url} />
              ) : (
                hasVideoUrl()
              )}
            </>
          )}
          {(type === 'plv' || type === 'bjy') && (
            <div className={styles.plvplayer} id="zhy-cjjoy-video-player" />
          )}
        </div>
        {(type === 'star' || type === 'score' || type === 'detail') && (
          <div className={styles.student}>
            <div className={styles.studentleft}>
              <i
                className={styles.avatar}
                style={{ backgroundImage: `url(${currentData?.avatar})` }}
                onClick={goStudent}
              />
              <div className={styles.nick} onClick={goStudent}>
                {currentData?.username}
              </div>
              <div className={styles.no}>学号：{currentData?.studentnum}</div>
            </div>
            {showDownLoadWorkFile && detail?.downfile && (
              <a
                href={detail?.downfile}
                target="_blank"
                className={styles.downloadfile}
                rel="noreferrer"
              >
                下载源文件
              </a>
            )}
          </div>
        )}
        {type === 'star' && (
          <div className={styles.startwrapper}>
            <div
              className={classNames(styles.star, { [styles.actived]: detail?.gooded != '0' })}
              onClick={handleGood}
            >
              <i className={styles.icon} />
              <div className={styles.text}>{detail?.goodnum}</div>
            </div>
          </div>
        )}

        {type === 'score' && (
          <Score
            data={currentData}
            detail={detail}
            key={currentData?.url}
            onSubmit={handleScoreSubmit}
            isLast={index === data.length - 1}
            onClose={onClose}
          />
        )}

        <img
          className={styles.close}
          src={require('./images/icon-close.png')}
          alt=""
          onClick={() => onClose?.()}
        />
        {data.length > 1 && (
          <>
            <i
              className={classNames(styles.prve, { [styles.disabled]: index === 0 })}
              onClick={handlePrev}
            />
            <i
              className={classNames(styles.next, { [styles.disabled]: index === data.length - 1 })}
              onClick={handleNext}
            />
          </>
        )}
      </div>
    </div>
  );
  return ReactDOM.createPortal(
    // 这里可以是dom元素,也可以是react组件,还可以是react节点
    content,
    // 将传入的元素/组件/节点,挂载到container下面
    container,
  );
};

// 点赞
const showStar = (
  options: Pick<OriginVideoPlayerModalProps, 'data' | 'onClose' | 'defaultIndex'>,
) => {
  const { data = [], defaultIndex, onClose } = options || {};
  const container = document.createElement('div');
  container.setAttribute('id', uid() + '' + Date.now());
  document.body.appendChild(container);
  const handleClose = () => {
    onClose?.();
    ReactDOM.unmountComponentAtNode(container);
    document.body.removeChild(container);
  };
  ReactDOM.render(
    <OriginVideoPlayerModal
      type="star"
      data={data}
      defaultIndex={defaultIndex}
      container={container}
      visible={true}
      destroyOnClose
      onClose={handleClose}
    />,
    container,
  );
};

// 评分
const showScore = (
  options: Pick<OriginVideoPlayerModalProps, 'data' | 'onClose' | 'defaultIndex' | 'onScoreSubmit'>,
) => {
  const { data = [], defaultIndex, onClose, onScoreSubmit } = options || {};
  const container = document.createElement('div');
  container.setAttribute('id', uid() + '' + Date.now());
  document.body.appendChild(container);
  const handleClose = () => {
    onClose?.();
    document.body.removeChild(container);
  };

  ReactDOM.render(
    <OriginVideoPlayerModal
      type="score"
      data={data}
      defaultIndex={defaultIndex}
      container={container}
      visible={true}
      onClose={handleClose}
      onScoreSubmit={onScoreSubmit}
      showDownLoadWorkFile
    />,
    container,
  );
  window.scrollTo({
    left: 0,
    top: 0,
  });
};

// 就弹窗看video
const showList = (
  options: Pick<OriginVideoPlayerModalProps, 'data' | 'onClose' | 'defaultIndex'>,
) => {
  const { data = [], defaultIndex, onClose } = options || {};
  const container = document.createElement('div');
  container.setAttribute('id', uid() + '' + Date.now());
  document.body.appendChild(container);
  const handleClose = () => {
    onClose?.();
    document.body.removeChild(container);
  };
  ReactDOM.render(
    <OriginVideoPlayerModal
      type="video"
      data={data}
      defaultIndex={defaultIndex}
      container={container}
      visible={true}
      onClose={handleClose}
    />,
    container,
  );
};

// 就弹窗看详情
const showListWithDetail = (
  options: Pick<
    OriginVideoPlayerModalProps,
    'data' | 'onClose' | 'defaultIndex' | 'showDownLoadWorkFile'
  >,
) => {
  const { data = [], defaultIndex, onClose, showDownLoadWorkFile } = options || {};
  const container = document.createElement('div');
  container.setAttribute('id', uid() + '' + Date.now());
  document.body.appendChild(container);
  const handleClose = () => {
    onClose?.();
    document.body.removeChild(container);
  };
  ReactDOM.render(
    <OriginVideoPlayerModal
      type="detail"
      data={data}
      defaultIndex={defaultIndex}
      container={container}
      visible={true}
      onClose={handleClose}
      showDownLoadWorkFile={showDownLoadWorkFile}
    />,
    container,
  );
};

// 保利威视频播放
const showPlvVideo = (
  options: Pick<OriginVideoPlayerModalProps, 'data' | 'onClose' | 'defaultIndex'>,
) => {
  const { data = [], defaultIndex, onClose } = options || {};
  const container = document.createElement('div');
  container.setAttribute('id', uid() + '' + Date.now());
  document.body.appendChild(container);
  const handleClose = () => {
    onClose?.();
    document.body.removeChild(container);
  };
  ReactDOM.render(
    <OriginVideoPlayerModal
      type="bjy"
      data={data}
      defaultIndex={defaultIndex}
      container={container}
      visible={true}
      onClose={handleClose}
    />,
    container,
  );
};

type VideoPlayerModalType = typeof OriginVideoPlayerModal & {
  showStar: typeof showStar;
  showScore: typeof showScore;
  showList: typeof showList;
  showListWithDetail: typeof showListWithDetail;
  showPlvVideo: typeof showPlvVideo;
};
const VideoPlayerModal = OriginVideoPlayerModal as VideoPlayerModalType;
VideoPlayerModal.showStar = showStar;
VideoPlayerModal.showScore = showScore;
VideoPlayerModal.showList = showList;
VideoPlayerModal.showListWithDetail = showListWithDetail;
VideoPlayerModal.showPlvVideo = showPlvVideo;

export default VideoPlayerModal;
